/*
 * Copyright (c) 2017 22420103@QQ.COM 版权所有
 */
package com.lehe.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.lehe.common.Contants;
import com.lehe.common.exceptions.LHException;
import com.lehe.common.exceptions.LHServiceException;
import com.lehe.common.utils.StringUtil;
import com.lehe.dao.GameUserDao;
import com.lehe.dao.GoldDetailDao;
import com.lehe.dao.UserInfoDao;
import com.lehe.entry.UserInfoDto;
import com.lehe.entry.dbbean.GameUserDto;
import com.lehe.entry.wx.message.RespUserOpenIdMessage;
import com.lehe.entry.wx.message.RespUserUnionIdMessage;
import com.lehe.service.IWeChatExecuteService;

/**
 * 用户账户操作
 *
 * @author 王丹
 * @since 2017-02-26
 */
@Transactional
@Service
public class UserInfoService extends AbstractService {

	@Autowired
    private UserInfoDao userInfoDao;

	@Autowired
    private GoldDetailDao goldDetailDao;
	
	@Autowired
    private GameUserDao gameUserDao;
    @Autowired
    @Qualifier("queryUserOpenIdExecuteService")
    private IWeChatExecuteService queryUserOpenIdExecuteService;
    @Autowired
    @Qualifier("queryUserUnionidIdExecuteService")
    private IWeChatExecuteService queryUserUnionidIdExecuteService;

    /**
     * 根据微信返回的code调用微信接口返回unionId
     * @param wxCode
     * @return
     * @throws LHException
     */
    public Map<String, String> invokeWxForUnionId(String wxCode) throws LHException {
        String wxOpenId = "";
        String wxUnionId = "";
        String nickName = "";
        String imgUrl = "";
        String sex = "";
        String address = "";
        try {
            Map<String, String> map = new HashMap<String, String>();
            map.put("appid", Contants.APP_ID);
            map.put("secret", Contants.APP_SECRET);
            map.put("grant_type", Contants.GRANT_TYPE_QUERY_OPENID);
            map.put("code", wxCode);

            RespUserOpenIdMessage respUserOpenIdMessage = (RespUserOpenIdMessage)queryUserOpenIdExecuteService.execute(map);
            if(StringUtil.isBlank(respUserOpenIdMessage.getOpenid())){
                throw new LHException("请在微信公众号中打开");
            }
            map.clear();
            map.put("access_token", respUserOpenIdMessage.getAccessToken());
            map.put("openid", respUserOpenIdMessage.getOpenid());
            map.put("lang", "zh_CN");
            //https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN
            RespUserUnionIdMessage respUserUnionIdMessage = (RespUserUnionIdMessage)queryUserUnionidIdExecuteService.execute(map);
            wxUnionId = respUserUnionIdMessage.getUnionid();
            wxOpenId = respUserOpenIdMessage.getOpenid();
            nickName = respUserUnionIdMessage.getNickname();
            sex = respUserUnionIdMessage.getSex();
            imgUrl = respUserUnionIdMessage.getHeadimgurl();
            address = (respUserUnionIdMessage.getCountry()==null?"":respUserUnionIdMessage.getCountry() )+
            		  (respUserUnionIdMessage.getProvince()==null?"":respUserUnionIdMessage.getProvince() )+
            		  (respUserUnionIdMessage.getCity()==null?"":respUserUnionIdMessage.getCity());
        } catch (LHServiceException e) {
            logger.error("获取wxUnionId失败:", e);
        }
        if(StringUtil.isBlank(wxUnionId)){
            throw new LHException("服务忙，请稍后重试");
        }
        Map<String, String> retMap = new HashMap<>();
        retMap.put("wxUnionId", wxUnionId);
        retMap.put("wxOpenId", wxOpenId);
        retMap.put("nickName", nickName);
        retMap.put("sex", sex);
        retMap.put("imgUrl", imgUrl);
        retMap.put("address", address);
        retMap.put("wxOpenId", wxOpenId);
        return retMap;
    }

    /**
     * 根据用户ID或者微信UnionId查找用户信息
     * @param userId
     * @param wxUnionId
     * @return
     */
    public UserInfoDto queryUserInfo(Long userId, String wxUnionId){
        UserInfoDto userInfoDto = new UserInfoDto();
        userInfoDto.setUserId(userId);
        userInfoDto.setWxUnionId(wxUnionId);
        return userInfoDao.queryUserInfo(userInfoDto);
    }

    /**
     * 授权代理更新用户账户信息
     * @param userInfoDto
     * @return
     */
    public int updateAccountByUserId(UserInfoDto userInfoDto){
        return userInfoDao.updateAccountByUserId(userInfoDto);
    }

	public UserInfoDto queryUserInfoByAgentId(Long agentId) {
		return userInfoDao.queryUserInfoByAgentId(agentId);
	}

    public boolean hasWhiteUser(Long userId){
        int count = userInfoDao.hasWhiteUser(userId);
        return count > 0;
    }

	public Map register(String userId, String wxUnionId, String wxOpenId, String nickName, String imgUrl, String sex, String address, String ip) {
		logger.info("二维码邀请人userid={}，nickName={}", userId, nickName);
        Map register = new HashMap();
		long userIdL=Long.valueOf(userId);
		GameUserDto parentGameUser = goldDetailDao.queryGameUserByUser(userIdL);
		
		GameUserDto accounts = goldDetailDao.queryAccountsInfoByUnionID(wxUnionId);
		
		GameUserDto queryGameUserByUser=null;
		boolean newUser=false;
		Long inserUserId= null;
		//如果未注册过 则调用注册逻辑
		if(accounts==null || accounts.getUserId()==null){
			Map<String,Object> p = new HashMap<String,Object>();
			p.put("userId", userId);
			p.put("wxUnionId", wxUnionId);
			p.put("wxOpenId", wxOpenId);
			p.put("nickName", nickName);
			p.put("imgUrl", imgUrl);
			p.put("sex", sex);
			p.put("address", address);
			p.put("ip", ip);
			register = userInfoDao.register(p);
			if((Integer)register.get("ResultCode")==0){
				inserUserId=((Integer)register.get("UserID")).longValue();
				newUser=true;
			}
			//注册未成功 或者 不是已经已经注册过了 的直接返回
			if((Integer)register.get("ResultCode")!=0 && (Integer)register.get("ResultCode")!=2){
				return register;
			}
		}else{
			inserUserId=accounts.getUserId();
			queryGameUserByUser = goldDetailDao.queryGameUserByUser(accounts.getUserId());
		}
        logger.info("扫描二维码注册userid={}", inserUserId);
		//如果（推荐人不在代理关系表）  或者 （推荐人运营号为空） 或者 （推荐人为玩家，但代理信息为空） 则直接忽略
		if(parentGameUser==null || parentGameUser.getTopId() == null ||(parentGameUser.getParentId() == null && parentGameUser.getUtype()==0)){
			return register;
		}	
		//如果 此次的注册者为新用户 或者 注册者的上级信息为空 则确定代理关系
		if(newUser || queryGameUserByUser==null){
			GameUserDto gameUserDto = new GameUserDto();
			gameUserDto.setCrtDate(new Date());
			gameUserDto.setCrtOpr(1l);
            if(parentGameUser.getUtype() == 1){
                gameUserDto.setParentId(userIdL);
            }else{
                gameUserDto.setParentId(parentGameUser.getParentId());
            }
			gameUserDto.setUserName(nickName);
			gameUserDto.setTopId(parentGameUser.getTopId());
			gameUserDto.setUserId(inserUserId);
			gameUserDto.setUtype(0);
			
			gameUserDao.insert(gameUserDto);
		}
		return register;
	}
}
